package cc.rengu.igas.share.core.service.channel.alipay;

import cc.rengu.igas.channel.alipay.facade.base.Header;
import cc.rengu.igas.channel.alipay.facade.bean.TradeFundBill;
import cc.rengu.igas.channel.alipay.facade.request.AliQueryOrderRequest;
import cc.rengu.igas.channel.alipay.facade.response.AliQueryOrderResponse;
import cc.rengu.igas.channel.alipay.facade.result.Result;
import cc.rengu.igas.share.common.constant.ShareParamConstant;
import cc.rengu.igas.share.common.constant.ShareServiceConstant;
import cc.rengu.igas.share.common.constant.TransCacheConstant;
import cc.rengu.igas.share.common.enums.AliPayStatusEnum;
import cc.rengu.igas.share.common.enums.FeeTypeEnum;
import cc.rengu.igas.share.core.model.MchntInfo;
import cc.rengu.igas.share.core.realize.MchntService;
import cc.rengu.igas.share.core.realize.impl.MchntServiceImpl;
import cc.rengu.oltp.service.base.ChannelBaseService;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.*;
import cc.rengu.oltp.service.common.enums.*;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.OrderInfo;
import cc.rengu.oltp.service.model.TxnInfo;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 支付宝查询支付
 * Created by lzl on 2021/4/23 11:08
 */
public class AliQueryOrderService extends ChannelBaseService {
    @Override
    public Object callPreProc(TxnInfo txnInfo, ChannelCallCfg channelCallCfg, OrderInfo orderInfo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        Header aliHeader = new Header();
        aliHeader.setInstId(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID));
        aliHeader.setChanlId(channelCallCfg.getMsgSrcId());
        aliHeader.setSrcSysId(AppParamConstant.SYS_ID);
        aliHeader.setBizType(AppParamConstant.DEFAULT_BIZ_TYPE);
        aliHeader.setVersion(ShareParamConstant.DUBBO_VSERSION);
        aliHeader.setTxnNum(channelCallCfg.getCallChannelTxn());
        aliHeader.setTraceNo(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM) + channelCallCfg.getCallIndex());
        aliHeader.setTransTime(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_TIME));
        aliHeader.setTransDate(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_DATE));

        MchntService mchntService = new MchntServiceImpl();
        MchntInfo mchntInfo = mchntService.getMchntInfo(aliHeader.getInstId(), orderInfo.getMchntOrderInfoList().get(0).getMchntNo());
        AliQueryOrderRequest alipayQueryOrderRequest = new AliQueryOrderRequest();

        ConvertUtil.convertOutput(alipayQueryOrderRequest);
        alipayQueryOrderRequest.setHeader(aliHeader);
        alipayQueryOrderRequest.setChannelId(channelCallCfg.getCallChannelId());
        alipayQueryOrderRequest.setChannelType(mchntInfo.getAlipayChannelType());
        alipayQueryOrderRequest.setAppAuthToken(mchntInfo.getAlipayAppAuthToken());
        Predicate<PayOrderInfo> channelFilter = p -> channelCallCfg.getCallChannelId().equals(p.getMsgDstId());
        List<PayOrderInfo> payOrderInfoList = orderInfo.getPayOrderInfoList().stream().filter(channelFilter).collect(Collectors.toList());
        alipayQueryOrderRequest.setOrderId(Objects.requireNonNull(payOrderInfoList.get(0)).getSysSeqNum());
        /*设置网联idc标识*/
        if (ChannelEnum.NUAL.getChannelType().equals(channelCallCfg.getCallChannelId())) {
            alipayQueryOrderRequest.setIdcFlag(payOrderInfoList.get(0).getRemark1());
        }
        rglog.debug("支付宝查询订单请求:<{}>", JSON.toJSONString(alipayQueryOrderRequest));
        return alipayQueryOrderRequest;
    }

    @Override
    public PayOrderInfo generatePayOrderInfo(ChannelCallCfg channelCallCfg, OrderInfo orderInfo, Object request) throws Exception {
        return null;
    }

    @Override
    public Object callProc(ChannelCallCfg channelCallCfg, Object request) throws Exception {
        AliQueryOrderRequest alipayQueryOrderRequest = (AliQueryOrderRequest) request;
        /* Step1：调用接口，获取结果 */
        Result<AliQueryOrderResponse> callResult;
        DubboService dubboService = new DubboServiceImpl();
        if (AppParamConstant.YES.equals(channelCallCfg.getSyncCallFlag())) {
            /* Step1.1：异步调用 */
            int iReturnCode;
            int callTimes = 0 == channelCallCfg.getSyncQueryRepeatNum() ? 1 : channelCallCfg.getSyncQueryRepeatNum();
            int gatTime = channelCallCfg.getSyncQueryRepeatTime();
            int gatType = StringUtil.isEmptyOrNull(channelCallCfg.getSyncQueryGapType()) ? 0 : Integer.parseInt(channelCallCfg.getSyncQueryGapType());
            if (ChannelCallModeEnum.LOCAL.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.1.1：异步应用内调用 */
                Class clasz = Class.forName(ShareServiceConstant.ALIPAY_PAY_SERVICE_INNER_PATH);
                iReturnCode = dubboService.asynCallDubboInnerMethod(clasz, ShareServiceConstant.ALI_QUERY_ORDER_METHOD, alipayQueryOrderRequest, channelCallCfg.getSyncResultServiceName(), callTimes, gatType, gatTime);
            } else if (ChannelCallModeEnum.REMOTE.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.1.2：异步远程调用 */
                iReturnCode = dubboService.asynCallDubboService(ShareServiceConstant.ALIPAY_PAY_SERVICE, ShareServiceConstant.ALI_QUERY_ORDER_METHOD, alipayQueryOrderRequest, channelCallCfg.getSyncResultServiceName(), callTimes, gatType, gatTime);
            } else {
                rglog.error("不支持的通道服务调用方式:{}，交易拒绝!", channelCallCfg.getChannelCallMode());
                throw new BizException(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR);
            }
            if (0 == iReturnCode) {
                return new BizResponse<>(OltpRpcdEnum.TRANS_SUCCESS.getRespCode(), OltpRpcdEnum.TRANS_SUCCESS.getRespDesc());
            } else {
                return new BizResponse<>(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
            }
        } else {
            /* Step1.2：同步调用 */
            if (ChannelCallModeEnum.LOCAL.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.2.1：同步应用内调用 */
                Class clasz = Class.forName(ShareServiceConstant.ALIPAY_PAY_SERVICE_INNER_PATH);
                callResult = (Result<AliQueryOrderResponse>) dubboService.callDubboInnerMethod(clasz, ShareServiceConstant.ALI_QUERY_ORDER_METHOD, alipayQueryOrderRequest);
            } else if (ChannelCallModeEnum.REMOTE.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.2.2：同步远程调用 */
                callResult = (Result<AliQueryOrderResponse>) dubboService.callDubboService(ShareServiceConstant.ALIPAY_PAY_SERVICE, ShareServiceConstant.ALI_QUERY_ORDER_METHOD, alipayQueryOrderRequest);
            } else {
                rglog.error("不支持的通道服务调用方式:{}，交易拒绝!", channelCallCfg.getChannelCallMode());
                throw new BizException(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR);
            }
        }
        return callResult;
    }

    @Override
    public Object querySyncCallResult(PayOrderInfo payOrderInfo, Object request) {
        return null;
    }

    @Override
    public OrderInfo callResultOrderProc(OrderInfo orderInfo, String payOrderIndex, TransStatusEnum transStatusEnum, Object response) throws Exception {
        OrderInfo updateOrderInfo = new OrderInfo();
        Result<AliQueryOrderResponse> callResult = (Result<AliQueryOrderResponse>) response;
        Optional<PayOrderInfo> payOrderInfoOpt = orderInfo.getPayOrderInfoList().stream().filter(item -> item.getMsgDstId().equals(ChannelEnum.ALIP.getChannelType()) ||
                item.getMsgDstId().equals(ChannelEnum.UPAL.getChannelType()) || item.getMsgDstId().equals(ChannelEnum.NUAL.getChannelType())).findFirst();
        if (payOrderInfoOpt.isPresent() && null != callResult && null != callResult.getResult()) {
            AliQueryOrderResponse aliQueryOrderResponse = callResult.getResult();
            UserOrderInfo userOrderInfo = orderInfo.getUserOrderInfo();
            List<MchntOrderInfo> mchntOrderInfoList = orderInfo.getMchntOrderInfoList();
            PayOrderInfo payOrderInfo = payOrderInfoOpt.get();
            payOrderInfo.setTransStatus(transStatusEnum.getStatus());
            payOrderInfo.setRespCode(aliQueryOrderResponse.getRespCode());
            payOrderInfo.setRespDesc(aliQueryOrderResponse.getRespDesc());
            payOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
            switch (transStatusEnum) {
                case TRANS_SUCC:
                    if (AliPayStatusEnum.TRADE_SUCCESS.getStatus().equals(aliQueryOrderResponse.getTradeStatus())) {
                        /* 更新支付订单信息 */
                        userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());
                        userOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
                        userOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
                        userOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
                        /* 更新商户订单信息 */
                        for (MchntOrderInfo mchntOrderInfo : mchntOrderInfoList) {
                            mchntOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
                            mchntOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
                            mchntOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
                        }
                        /* 判断商户是否在通道有配置营销,若有配置，则需要更新商户订单信息 */
                        String mchntDiscAmt = "0";
                        if (!StringUtil.isEmptyOrNull(aliQueryOrderResponse.getSettleAmt())) {
                            mchntDiscAmt = AmountUtil.subtraction(payOrderInfo.getRealPayAmt(), aliQueryOrderResponse.getSettleAmt());
                        }
                        if (AmountUtil.compare(mchntDiscAmt, "0.00") == 1) {
                            /* 更新用户订单表中的实际支付金额及实际优惠金额 */
                            userOrderInfo.setRealDiscountAmt(AmountUtil.addition(userOrderInfo.getRealDiscountAmt(), mchntDiscAmt));
                            userOrderInfo.setRealPayAmt(AmountUtil.subtraction(userOrderInfo.getRealPayAmt(), mchntDiscAmt));
                            /* 计算每个商户的优惠金额 */
                            String mchntPerDiscAmt = AmountUtil.division(mchntDiscAmt, String.valueOf(mchntOrderInfoList.size()), 2);
                            String lastMchntRealSettleAmt = mchntOrderInfoList.get(mchntOrderInfoList.size() - 1).getRealSettleAmt();
                            mchntOrderInfoList.forEach(item -> item.setRealSettleAmt(AmountUtil.subtraction(item.getRealSettleAmt(), mchntPerDiscAmt)));
                            /* 重新赋值最后一个商户的实际清算本金 */
                            String lastMchntDiscAmt = AmountUtil.subtraction(mchntDiscAmt, AmountUtil.multiplication(mchntPerDiscAmt, String.valueOf(mchntOrderInfoList.size() - 1), 2));
                            mchntOrderInfoList.get(mchntOrderInfoList.size() - 1).setRealSettleAmt(AmountUtil.subtraction(lastMchntRealSettleAmt, lastMchntDiscAmt));
                            /* 若商户有计算手续费，则重新计算商户手续费 */
                            MchntService mchntService = new MchntServiceImpl();
                            mchntService.calcMchntFee(mchntOrderInfoList, FeeTypeEnum.ALIPAY.getFeeType());
                        }
                        updateOrderInfo.setUserOrderInfo(userOrderInfo);
                        updateOrderInfo.setMchntOrderInfoList(mchntOrderInfoList);
                        /* 更新支付订单信息 */
                        payOrderInfo.setPayerAcctType(AcctTypeEnum.ALL.getAcctType());
                        List<TradeFundBill> tradeFundBillList = aliQueryOrderResponse.getTradeFundBillList();
                        if (null != tradeFundBillList && !tradeFundBillList.isEmpty()) {
                            if ("DEBIT_CARD".equals(tradeFundBillList.get(0).getFundType())) {
                                payOrderInfo.setPayerAcctType(AcctTypeEnum.OTHER_DEBIT.getAcctType());
                            } else {
                                payOrderInfo.setPayerAcctType(AcctTypeEnum.OTHER_CREDIT.getAcctType());
                            }
                        }
                        payOrderInfo.setPayerAcctInfo(aliQueryOrderResponse.getBuyerLogonId());
                        payOrderInfo.setRespCode(aliQueryOrderResponse.getRespCode());
                        payOrderInfo.setRespDesc(aliQueryOrderResponse.getRespDesc());
                        payOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
                        payOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
                        payOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
                    } else if (AliPayStatusEnum.TRADE_CLOSED.getStatus().equals(aliQueryOrderResponse.getTradeStatus())) {
                        userOrderInfo.setOrderStatus(OrderStatusEnum.CLOSE.getStatus());
                        userOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
                        userOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
                        mchntOrderInfoList.forEach(item -> {
                            item.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
                            item.setBizStatus(BizStatusEnum.FAILED.getStatus());
                        });
                        updateOrderInfo.setUserOrderInfo(userOrderInfo);
                        updateOrderInfo.setMchntOrderInfoList(mchntOrderInfoList);
                        payOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
                        payOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
                    } else if (AliPayStatusEnum.WAIT_BUYER_PAY.getStatus().equals(aliQueryOrderResponse.getTradeStatus())) {
                        GlobalTransUtil.setCacheValue(TransCacheConstant.ORDER_PAY_FLAG,AppParamConstant.NO);
                        rglog.debug("订单用户支付中，订单状态不做更新!");
                    } else if (AliPayStatusEnum.TRADE_FINISHED.getStatus().equals(aliQueryOrderResponse.getTradeStatus())) {
                        rglog.debug("交易结束，不可退款!");
                        userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());
                        userOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
                        userOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
                        mchntOrderInfoList.forEach(item -> {
                            item.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
                            item.setBizStatus(BizStatusEnum.FAILED.getStatus());
                        });
                        updateOrderInfo.setUserOrderInfo(userOrderInfo);
                        updateOrderInfo.setMchntOrderInfoList(mchntOrderInfoList);
                        payOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
                        payOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
                    }
                    break;
                case TRANS_TIMEOUT:
                    payOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
                    break;
                case SYSTEM_REJECT:
                    if ("10003".equals(aliQueryOrderResponse.getRespCode()) || "20000".equals(aliQueryOrderResponse.getRespCode())) {
                        /*用户支付中，不做任何处理，在发起的异步查证中处理,用户订单和商户订单不做修改更新 */
                        payOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
                        payOrderInfo.setTransStatus(TransStatusEnum.TRANS_INIT.getStatus());
                    } else {
                        payOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
                    }
                    break;
                default:
                    break;
            }
            updateOrderInfo.setPayOrderInfoList(Collections.singletonList(payOrderInfo));
        }
        return updateOrderInfo;
    }

}
